package com.xiaoxing.zhinenghuacangku_jining.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.printer.IDzPrinter;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.zhinenghuacangku_jining.R;
import com.xiaoxing.zhinenghuacangku_jining.R2;
import com.xiaoxing.zhinenghuacangku_jining.di.component.DaggerJiNing_ZhiJianRuKuComponent;
import com.xiaoxing.zhinenghuacangku_jining.di.module.JiNing_ZhiJianRuKuModule;
import com.xiaoxing.zhinenghuacangku_jining.mvp.contract.JiNing_ZhiJianRuKuContract;
import com.xiaoxing.zhinenghuacangku_jining.mvp.model.entity.JiNing_GetDistributeList;
import com.xiaoxing.zhinenghuacangku_jining.mvp.model.entity.JiNing_GetUserSpaceListForAutoStore;
import com.xiaoxing.zhinenghuacangku_jining.mvp.presenter.JiNing_ZhiJianRuKuPresenter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.entity.JiNing_ZhiJianRuKu;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.utils.LogWriter;
import com.xiaoxing.zhinenghuacangku_jining.mvp.ui.utils.PrinterUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import pub.devrel.easypermissions.EasyPermissions;

import static com.jess.arms.base.BaseConstants.SCAN_REQUEST_CODE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_JINING_ACTIVITY_ZHI_JIAN_RU_KU)
public class JiNing_ZhiJianRuKuActivity extends BaseActivity<JiNing_ZhiJianRuKuPresenter> implements JiNing_ZhiJianRuKuContract.View, EasyPermissions.PermissionCallbacks, PrinterUtil.PrinterI {
    @BindView(R2.id.nice_storage)
    NiceSpinner spStorage;
    @BindView(R2.id.ll_search_material)
    LinearLayout llSearchMaterial;
    @BindView(R2.id.nice_position)
    NiceSpinner spPosition;
    @BindView(R2.id.btn_scan_qr_code)
    Button btnScanQrCode;
    @BindView(R2.id.btn_generate_tags)
    Button btnGenerateTags;
    @BindView(R2.id.btn_confirm_storage)
    Button btnConfirmStorage;
    @BindView(R2.id.btn_scan_mid)
    Button btnScanMid; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.cb_er_wei_ma)
    CheckBox cbErWeiMa; //扫描物料二维码(有二维码的质检样品)
    @BindView(R2.id.et_dan_hao)
    EditText etDanHao;
    @BindView(R2.id.et_xiang_mu_ming_cheng)
    EditText etXiangMuMingCheng;
    @BindView(R2.id.et_xiang_mu_bian_hao)
    EditText etXiangMuBianHao;
    @BindView(R2.id.et_wu_liao_ming_cheng)
    EditText etWuLiaoMingCheng;
    @BindView(R2.id.et_gong_ying_shang)
    EditText etGongYingShang;
    @BindView(R2.id.tv_cha_xun)
    TextView tvChaXun;
    @BindView(R2.id.et_weizhi)
    EditText etWeizhi;
    @BindView(R2.id.tv_check)
    TextView tvCheck;
    @BindView(R2.id.tv_agv_huan_chong_wei)
    TextView tvAgvHuanChongWei;
    @BindView(R2.id.et_num)
    EditText et_num;
    @BindView(R2.id.et_remark)
    EditText et_remark;
    PrinterUtil mPrinterUtil;
    private BottomDialogUtil mBottomDialogUtilShare;
    private boolean isScan = false; //是否扫描二维码
    private boolean isGenerateTags = false; // 是否生成、打印标签
    private boolean isConfirmStorage = false; //是否确定入库
    private int did = 0;
    private double num = 0;
    private String imgStr = "";
    private String cangWeiPosition = "";
    private String mid = "";
    private String instoreBufferId = "";
    private int spid = 0;
    private String spname = "";
    private TextWatcher numTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            String etNum = et_num.getText().toString();
            if (!TextUtils.isEmpty(etNum) && Double.parseDouble(etNum) > 0) {
                if (Double.parseDouble(etNum) > num) {
                    et_num.setText(num + "");
                    ArmsUtils.makeText(getContext(), "数量不能大于" + num);
                    return;
                }
//                num = Double.parseDouble(et_num.getText().toString());
            }


        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private String mOrderNo = "";
    private String mWuLiaoMingCheng = "";
    private String mXiangMuBianHao = "";
    private LogWriter mLogWriter;
    private int mGid = 0;
    private String mSptname;
    private String mScanSpid = "";
    /**
     * 初始化缓冲位列表下拉选
     */
    private ArrayList<String> mSpids;
    private String mScanMid = "";

    public static byte[] strToByteArray(String str) {
        if (str == null) {
            return null;
        }
        byte[] byteArray = str.getBytes();
        return byteArray;
    }

    public static Bitmap getBitmap(String filePath) {

        Bitmap bitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
                (double) options.outWidth / 1024f,
                (double) options.outHeight / 1024f)));
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        return bitmap;
    }

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerJiNing_ZhiJianRuKuComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .jiNing_ZhiJianRuKuModule(new JiNing_ZhiJianRuKuModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.zhi_neng_cang_ku_ji_ning_activity_jian_xiu_ru_ku; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        File logf = new File(Environment.getExternalStorageDirectory() + File.separator + "cangkuguanli-" + ArmsUtils.getDataTime("yyyy-MM-dd HH:mm") + ".txt");

        try {
            mLogWriter = LogWriter.open(logf.getAbsolutePath());
        } catch (Exception e) {
        }

        log("22222222222222222");
//        ToolbarUtils.initToolbarTitleBack(this, "入库");
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView tvTitle = findViewById(R.id.title);

        tvTitle.setText("质检入库");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(instoreBufferId)) {
                    showConfirmMessageDialog();
                } else {
                    finish();
                }
            }
        });

        PhotoUtil.init(this, new FrescoIniter());
        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(false);
        et_num.addTextChangedListener(numTextWatcher);

        if (isLinYi) {
            btnScanQrCode.setText("扫描库位");
            cbErWeiMa.setVisibility(View.VISIBLE);
            cbErWeiMa.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        btnScanMid.setVisibility(View.VISIBLE);
                        llSearchMaterial.setVisibility(View.GONE);
                        spStorage.setVisibility(View.GONE);
                    } else {
                        btnScanMid.setVisibility(View.GONE);
                        llSearchMaterial.setVisibility(View.VISIBLE);
                        spStorage.setVisibility(View.VISIBLE);
                    }
                }
            });
        }

    }

    public void log(String msg) {

        try {
            mLogWriter.print(JiNing_StorageActivity.class, msg);
        } catch (Exception e) {
        }
    }

    private void showConfirmMessageDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(this)
                .setTitle("确认退出?")
                .setMessage("已扫描缓冲位,确认退出?")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
//                        mPresenter.cancelBufferReadyForAGV(getContext(), instoreBufferId);
                        cancelBufferReadyForAGV(instoreBufferId);
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void cancelBufferReadyForAGV(String bufferId) {

        showLoading();

        String methodName = "CancelBufferReadyForAGV";

        SoapParams params = new SoapParams();
        params.put("bufferId", bufferId);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    finish();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog();

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(getContext(), message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            Bundle extras = data.getExtras();
            if (extras != null) {


                if (isLinYi) {
                    mScanSpid = extras.getString("scan_result");
                    //判断扫描的二维码是否在返回的列表中(二维码为spid)
                    if (mSpids.contains(mScanSpid)) { //在的话mScanSpid = spid
                        btnGenerateTags.setVisibility(View.GONE);
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
                        btnConfirmStorage.setEnabled(true);


                    } else { //不在的话，给个提示，instoreBufferId = spid ，然后把mScanSpid置为空
//                        instoreBufferId = mScanSpid;
                        mScanSpid = "";
                        showMessage("您扫描的二维码不在入库待检区库位中");
//                        setInstoreBufferReadyForAGV(instoreBufferId, spname);
                    }
                } else {
                    //isScan = true;
                    //tvAgvHuanChongWei.setVisibility(View.VISIBLE);
                    //tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(extras.getString("scan_result")));
                    instoreBufferId = extras.getString("scan_result");
                    //mPresenter.setInstoreBufferReadyForAGV(this, instoreBufferId, spname);
                    setInstoreBufferReadyForAGV(instoreBufferId, spname);
                }
            }

        } else if (resultCode == 102) {//扫描物料二维码(有二维码的质检样品)
            Bundle extras = data.getExtras();
            mid = extras.getString("scan_result");
            mScanMid = mid;
            btnGenerateTags.setVisibility(View.GONE);
            btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
            btnConfirmStorage.setEnabled(true);

        } else {
            if (resultCode != 0)
                PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void setInstoreBufferReadyForAGV(String bufferId, String spid) {

        showLoading();
        String methodName = "SetInstoreBufferReadyForAGV";

        SoapParams params = new SoapParams();
        params.put("bufferId", bufferId);
        params.put("spname", spid);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (result.equals("false")) {

                        //ArmsUtils.makeText(this, "1.此缓冲位已占满 2.此缓冲位没有启用 3.此缓冲位是出库缓冲位(标签贴错)");
                        ArmsUtils.makeText(getContext(), "缓冲位置不可用，请联系管理员");

                    } else {

                        isScan = true;
                        tvAgvHuanChongWei.setVisibility(View.VISIBLE);
                        tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

                        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnGenerateTags.setBackgroundColor(getResources().getColor(R.color.public_red));
                        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                        btnScanQrCode.setEnabled(false);
                        btnGenerateTags.setEnabled(true);
                        btnConfirmStorage.setEnabled(false);
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            xiuGaiTouXiang();
        }
    }

    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(JiNing_ZhiJianRuKuActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    log("相册选择图片：");
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(JiNing_ZhiJianRuKuActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    log("相机拍照：");
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log(e.getMessage());

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(getContext(), root);
        mBottomDialogUtilShare.showDiaolog();

    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        imgStr = ArmsUtils.bitmapToString(compressedPath);
//        HashMap<String, String> map = new HashMap<String, String>();
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));//运输计划ID
        params.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        params.put("num", et_num.getText().toString());
        params.put("imgStr", String.valueOf(imgStr));
        log("调用上传图片接口");

//        mPresenter.createMaterialForInstoreAuto(getContext(), map);
        createMaterialForInstoreAuto(params);
    }

    private void createMaterialForInstoreAuto(SoapParams params) {
        showLoading();


        String methodName = "CreateMaterialForInstoreAuto";


        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    if (!result.equals("-1")) {
                        mid = result;
                        log("上传图片成功后返回的要打印的mid：" + result);
                        try {

                            if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                                printQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            } else {
                                printBigQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                            }
                        } catch (Exception e) {
                            log(e.getMessage());
                        }
                    } else {
                        ArmsUtils.makeText(getContext(), "打印异常");
                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 小的纸张 50x20 的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 16 * 100, 0 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 15) {
            if (name.substring(15).length() > 20) {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 96 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 18 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
                api.drawText("入库时间:" + time, 16 * 100, 15 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 16 * 100, 3 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
            api.drawText("入库时间:" + time, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printQRcode");


//        }
    }

    /**
     * 大的纸张 50x50的
     *
     * @param content
     * @param orderNo
     * @param name
     * @param num
     * @param time
     * @param proid
     */
    private void printBigQRcode(String content, String orderNo, String name, String num, String time, String proid) {
//        if (mPrinterUtil.selectPrinterCheck()) {
        log("初始化打印二维码printBigQRcode");

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 50 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 10 * 100, 6 * 100, 25 * 100);//  9, 10, 20,30
        api.drawText("订单号:" + orderNo, 0 * 100, 32 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        if (name.length() > 25) {
            if (name.substring(25).length() > 20) {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15, 35), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(35), 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR,0);
                api.drawText("入库时间:" + time, 0 * 100, 50 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            } else {
                api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("物料名称:" + name.substring(0, 15), 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
                api.drawText("" + name.substring(15), 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR,0);
                api.drawText("入库时间:" + time, 0 * 100, 47 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            }

        } else {
            api.drawText("核对序号:" + content, 0 * 100, 35 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("项目编号:" + proid, 0 * 100, 38 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
            api.drawText("物料名称:" + name, 0 * 100, 41 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR,0);
            api.drawText("入库时间:" + time, 0 * 100, 44 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
        log("二维码打印成功printBigQRcode");

//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!TextUtils.isEmpty(instoreBufferId)) {
                showConfirmMessageDialog();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);


    }

    @OnClick({R2.id.btn_scan_qr_code, R2.id.btn_generate_tags, R2.id.btn_confirm_storage, R2.id.btn_scan_mid})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.btn_scan_qr_code) {
            if (getPermission()) {

                if (spid > 0) {

//            Utils.navigation(getContext(), RouterHub.ZHI_NENG_HUA_CANG_KU_LIN_YI_SCAN_QR_CODE_ACTIVITY, 101);
                    Intent newIntent = new Intent(this, JiNing_ScanQRCodeActivity.class);
                    mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 101);
                    // 开始一个新的 Activity等候返回结果
                    startActivityForResult(newIntent, 101);
                } else {
                    ArmsUtils.makeText(getContext(), "请先选择仓位");
                }

            }

        } else if (i == R.id.btn_scan_mid) {//扫描物料二维码(有二维码的质检样品)
            if (getPermission()) {

                if (spid > 0) {

                    Intent newIntent = new Intent(this, JiNing_ScanQRCodeActivity.class);
                    mSharedPreferencesHelper.putInt(SCAN_REQUEST_CODE, 102);
                    // 开始一个新的 Activity等候返回结果
                    startActivityForResult(newIntent, 102);
                } else {
                    ArmsUtils.makeText(getContext(), "请先选择仓位");
                }

            }

        } else if (i == R.id.btn_generate_tags) {
            if (mPrinterUtil.selectPrinterCheck()) {

                //num 用于判断是否选择物料
                if (did > 0 && num > 0) {

                    if (!isScan) {
                        ArmsUtils.makeText(getContext(), "请先扫描二维码");
                        return;
                    }
                    if (getPermission()) {
                        xiuGaiTouXiang();
                    }
                } else {
                    ArmsUtils.makeText(getContext(), "请先选择物料");
                }
            }

        } else if (i == R.id.btn_confirm_storage) {
            if (isLinYi) {

                if (!TextUtils.isEmpty(mScanMid)) {

                    linYinYouErWeiMaZhiJianYangPin(mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());

                } else {
                    if (getPermission()) {
                        if (TextUtils.isEmpty(imgStr)) {
                            xiuGaiTouXiang();
                        } else {
                            linYinShouDongRuKu(mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                        }
                    }
                }


            } else {
                if (!isScan) {
                    ArmsUtils.makeText(getContext(), "请先扫描二维码");
                    return;
                }
                if (!isGenerateTags) {
                    ArmsUtils.makeText(getContext(), "标签没有打印");
                    return;
                }
//            mPresenter.addAgvTask(this, mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());
                addAgvTask(mid, instoreBufferId, String.valueOf(spid), et_num.getText().toString(), mSharedPreferencesHelper.getString(BaseConstants.UID), et_remark.getText().toString().trim());

            }

        }
    }

    private boolean getPermission() {
        if (EasyPermissions.hasPermissions(this, permissions)) {
            return true;
        } else {
            EasyPermissions.requestPermissions(this, "需要获取您的相册、照相使用权限", 1, permissions);
            return false;
        }

    }

    private void addAgvTask(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "InstoreCallAGV";
        SoapParams params = new SoapParams();

        if (isLinYi) {
            //(2)入库函数 public string Instore(int did, int spid, int uid, double num, int status, string remark, string imgStr)
            //判断mScanSpid是否为空，不为空二维码在返回的仓位列表中，执行Instore 方法，为空的话执行InstoreCallAGV 方法
            if (!TextUtils.isEmpty(mScanSpid)) {
                methodName = "Instore";
                params.put("did", String.valueOf(did));
                params.put("spid", mScanSpid);
                params.put("uid", uid);
                params.put("num", num);
                params.put("status", "2");
                params.put("remark", remark);
                params.put("imgStr", imgStr);
            } else {
                methodName = "InstoreCallAGV";
                params.put("mid", mid);
                params.put("instoreBufferId", instoreBufferId);
                params.put("spid", spid);
                params.put("num", num);
                params.put("uid", uid);
                params.put("remark", remark);
            }

        } else {
            methodName = "InstoreCallAGV";
            params.put("mid", mid);
            params.put("instoreBufferId", instoreBufferId);
            params.put("spid", spid);
            params.put("num", num);
            params.put("uid", uid);
            params.put("remark", remark);
        }

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    isGenerateTags = false;
                    isScan = false;
                    btnScanQrCode.setBackgroundColor(getResources().getColor(R.color.public_red));
                    btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
                    btnScanQrCode.setEnabled(true);
                    btnGenerateTags.setEnabled(false);
                    btnConfirmStorage.setEnabled(false);
                    onChaXunClicked();
                    cangWeiChaXun();
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinYouErWeiMaZhiJianYangPin(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "InstoreCallAGVFromQualityZone";
        SoapParams params = new SoapParams();
        params.put("mid", mid);
        params.put("instoreBufferId", instoreBufferId);
        params.put("spid", spid);
        params.put("uid", uid);
        params.put("remark", remark);


        /**
         * 请求
         */

        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    mScanMid = "";

                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    private void linYinShouDongRuKu(String mid, String instoreBufferId, String spid, String num, String uid, String remark) {
        showLoading();

        String methodName = "Instore";
        SoapParams params = new SoapParams();
        params.put("did", String.valueOf(did));
        params.put("spid", mScanSpid);
        params.put("uid", uid);
        params.put("num", num);
        params.put("status", "2");
        params.put("remark", remark);
        params.put("imgStr", imgStr);


        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("-1")) {
                    try {
                        if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                            printQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        } else {
                            printBigQRcode(result, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                        }
                    } catch (Exception e) {
                        log(e.getMessage());
                    }
                    onChaXunClicked();
                    cangWeiChaXun();

                } else {
                    showMessage("入库失败");
                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "相关权限获取成功");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ArmsUtils.makeText(this, "请同意相关权限，否则功能无法使用");
    }


    @Override
    public void getZhiJianRuKuDataSuccess(JiNing_ZhiJianRuKu entityData) {

    }

    @Override
    public void getDistributeListSuccess(List<JiNing_GetDistributeList> getDistributeLists) {
        initSpStorage(getDistributeLists);
    }

    /**
     * 初始化入库列表下拉选
     */
    private void initSpStorage(List<JiNing_GetDistributeList> distributeLists) {


        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < distributeLists.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(distributeLists.get(i).getProjectName())
                            .append("-")
                            .append(distributeLists.get(i).getMaterial())
            ));
        }
        did = distributeLists.get(0).getDid();
        num = distributeLists.get(0).getDnum();
        et_num.setText(String.valueOf(num));
        mOrderNo = distributeLists.get(0).getPurchaseid();//打印二维码的订单号
        mWuLiaoMingCheng = distributeLists.get(0).getMaterial();//打印二维码的物料名称
        mXiangMuBianHao = distributeLists.get(0).getProid();//打印二维码的项目编号
        mGid = distributeLists.get(0).getGid();
        spStorage.attachDataSource(list);
        spStorage.setGravity(Gravity.LEFT);
        spStorage.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                did = distributeLists.get(position).getDid();
                num = distributeLists.get(position).getDnum();
                mOrderNo = distributeLists.get(position).getPurchaseid();
                mWuLiaoMingCheng = distributeLists.get(position).getMaterial();
                mXiangMuBianHao = distributeLists.get(position).getProid();
                mGid = distributeLists.get(position).getGid();

                et_num.setText(String.valueOf(num));
            }
        });

    }

    @Override
    public void getUserSpaceListForAutoStoreSuccess(List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        initSpPosition(getUserSpaceListForAutoStoreList);
    }

    private void initSpPosition(List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList) {
        ArrayList<String> list = new ArrayList<String>();
        mSpids = new ArrayList<String>();
        for (int i = 0; i < getUserSpaceListForAutoStoreList.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getUserSpaceListForAutoStoreList.get(i).getSpname())
            ));
            if (getUserSpaceListForAutoStoreList.get(i).getSptname().equals("入库待检区")) {
                mSpids.add(String.valueOf(getUserSpaceListForAutoStoreList.get(i).getSpid()));
            }
        }
        spid = getUserSpaceListForAutoStoreList.get(0).getSpid();
        spname = list.get(0);
        cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(0).getSpid());

        if (isLinYi) {
            mSptname = getUserSpaceListForAutoStoreList.get(0).getSptname();
            if (mSptname.equals("入库待检区")) {
                showMessage("仓管员扫描待检区二维码");
            }
        }

        spPosition.attachDataSource(list);
        spStorage.setGravity(Gravity.LEFT);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cangWeiPosition = String.valueOf(getUserSpaceListForAutoStoreList.get(position).getSpid());
                spid = getUserSpaceListForAutoStoreList.get(position).getSpid();
                spname = getUserSpaceListForAutoStoreList.get(position).getSpname();

                if (isLinYi) {
                    mSptname = getUserSpaceListForAutoStoreList.get(position).getSptname();
                    if (mSptname.equals("入库待检区")) {
                        showMessage("仓管员扫描待检区二维码");
                    }
                }
            }
        });
    }

    @Override
    public void createMaterialForInstoreAutoSuccess(String createMaterialForInstoreAuto) {
        if (!createMaterialForInstoreAuto.equals("-1")) {

            mid = createMaterialForInstoreAuto;
            log("上传图片成功后返回的要打印的mid：" + createMaterialForInstoreAuto);
            try {

                if (mSharedPreferencesHelper.getString(BaseConstants.ER_WEI_MA_TYPE).equals("1")) {
                    printQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                } else {
                    printBigQRcode(mid, mOrderNo, mWuLiaoMingCheng, et_num.getText().toString(), ArmsUtils.getDataTime("yyyy/MM/dd HH:mm:ss"), mXiangMuBianHao);
                }
            } catch (Exception e) {
                log(e.getMessage());
            }
        } else {
            ArmsUtils.makeText(getContext(), "打印异常");
        }
//        printQRcode(createMaterialForInstoreAuto);
//        showQueDingRuKuBtn();
    }

    @Override
    public void setInstoreBufferReadyForAGVSuccess(String setInstoreBufferReadyForAGV) {
        if (setInstoreBufferReadyForAGV.equals("false")) {

//            ArmsUtils.makeText(this, "1.此缓冲位已占满 2.此缓冲位没有启用 3.此缓冲位是出库缓冲位(标签贴错)");
            ArmsUtils.makeText(this, "缓冲位置不可用，请联系管理员");

        } else {

            isScan = true;
            tvAgvHuanChongWei.setVisibility(View.VISIBLE);
            tvAgvHuanChongWei.setText(new StringBuilder().append("已选择的Agv缓冲位置：").append(instoreBufferId));

            btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnGenerateTags.setBackgroundColor(getResources().getColor(R.color.public_red));
            btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
            btnScanQrCode.setEnabled(false);
            btnGenerateTags.setEnabled(true);
            btnConfirmStorage.setEnabled(false);
        }
    }

    @Override
    public void addAgvTaskSuccess(String addAgvTask) {
        isGenerateTags = false;
        isScan = false;
        btnScanQrCode.setBackgroundColor(getResources().getColor(R.color.public_red));
        btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnScanQrCode.setEnabled(true);
        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(false);
        onChaXunClicked();
        cangWeiChaXun();
    }

    @OnClick(R2.id.tv_cha_xun)
    public void onChaXunClicked() {

        if (TextUtils.isEmpty(getDanHao())
                && TextUtils.isEmpty(getXiangMuMingCheng())
                && TextUtils.isEmpty(getXiangMuBianHao())
                && TextUtils.isEmpty(getWuLiaoMingCheng())
                && TextUtils.isEmpty(getGongYingShang())) {

            ArmsUtils.makeText(this, "至少输入一个查询条件");

            return;

        }

        if (TextUtils.isEmpty(mSharedPreferencesHelper.getString(BaseConstants.UID))) {
            ArmsUtils.makeText(this, "请先登录");
            return;
        }
//        mPresenter.getDistributeList(this, mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
        getDistributeList(mSharedPreferencesHelper.getString(BaseConstants.UID), getDanHao(), getXiangMuMingCheng(), getWuLiaoMingCheng(), getXiangMuBianHao(), getGongYingShang());
    }

    @OnClick(R2.id.tv_check)
    public void cangWeiChaXun() {
//        if (TextUtils.isEmpty(getCangWei())) {
//            ArmsUtils.makeText(this, "请输入仓位的名称");
//            return;
//        }
        getUserSpaceListForAutoStore(getCangWei());

    }

    private String getDanHao() {
        return etDanHao.getText().toString().trim();
    }

    private String getXiangMuMingCheng() {
        return etXiangMuMingCheng.getText().toString().trim();
    }

    private String getXiangMuBianHao() {
        return etXiangMuBianHao.getText().toString().trim();
    }

    private String getWuLiaoMingCheng() {
        return etWuLiaoMingCheng.getText().toString().trim();
    }

    private String getGongYingShang() {
        return etGongYingShang.getText().toString().trim();
    }

    /**
     * 搜索获取物料列表
     *
     * @param user_id
     * @param orderNo
     * @param projectName
     * @param material
     * @param projectNo
     * @param sname
     * @return
     */
    private void getDistributeList(String user_id, String orderNo, String projectName, String material, String projectNo, String sname) {

        showLoading();

        String methodName = "GetDistributeList";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("orderNo", orderNo);
        params.put("projectName", projectName);
        params.put("material", material);
        params.put("projectNo", projectNo);
        params.put("sname", sname);

        /**
         * 请求
         */
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<JiNing_GetDistributeList> getDistributeLists = ArmsUtils.parseString2List(result, JiNing_GetDistributeList.class);
                    initSpStorage(getDistributeLists);

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 查询仓位
     *
     * @param spname
     */
    private void getUserSpaceListForAutoStore(String spname) {
//        mPresenter.getUserSpaceListForAutoStore(this, mSharedPreferencesHelper.getString(BaseConstants.UID), spname);
        getUserSpaceListForAutoStore(mSharedPreferencesHelper.getString(BaseConstants.UID), spname, mGid);
    }

    private String getCangWei() {
        return etWeizhi.getText().toString().trim();
    }

    /**
     * 选仓位
     * 用法同GetUserSpaceList
     * 多了一个字段 isauto，表明此仓位是否为立库仓位  用于提示用户
     *
     * @param user_id
     * @param spname  仓位的名字，为空的时候表示查询所有的
     * @return
     */

    private void getUserSpaceListForAutoStore(String user_id, String spname, int gid) {

        showLoading();

        String methodName = "GetUserSpaceListForAutoStore";
        SoapParams params = new SoapParams();
        params.put("user_id", user_id);
        params.put("spname", spname);
        if (isLinYi) {
            methodName = "GetUserSpaceListWithQualityCheck";
            if (gid != 0)
                params.put("gid", String.valueOf(gid));
        }

        /**
         * 请求
         */
        String finalMethodName = methodName;
        SoapUtil.getInstance(this).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();

                String result = object.getProperty(finalMethodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    List<JiNing_GetUserSpaceListForAutoStore> getUserSpaceListForAutoStoreList = ArmsUtils.parseString2List(result, JiNing_GetUserSpaceListForAutoStore.class);
                    initSpPosition(getUserSpaceListForAutoStoreList);

                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();
            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void cancelBufferReadyForAGVSuccess(String addAgvTask) {
        finish();
    }

    private void printQRcode(String content) {


        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.startJob(50 * 100, 20 * 100);//48, 50
        // 开始一个页面的绘制，绘制二维码
        api.draw2DQRCode(content, 0 * 100, 1 * 100, 15 * 100);//  9, 10, 20,30


        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {
        log(info);

    }

    @Override
    public void onPrintProgress(String info) {
        log(info);

    }

    @Override
    public void onPrinterDiscovery(String info) {
        log(info);

    }

    @Override
    public void connectSuccess(String info) {
        log("打印机连接成功，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void Connecting(String info) {
        log(info);

    }

    @Override
    public void connectFail(String info) {
        log("打印机连接失败、断开连接，发送通知，刷新界面提示:==" + info);

    }

    @Override
    public void printSuccess() {
        log("二维码打印成功");

        showQueDingRuKuBtn();
    }

    private void showQueDingRuKuBtn() {
        isGenerateTags = true;

        btnScanQrCode.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnGenerateTags.setBackground(getResources().getDrawable(R.drawable.public_shape_gray_bg_corner_5dp));
        btnConfirmStorage.setBackground(getResources().getDrawable(R.drawable.public_shape_red_bg_corner_5dp));
        btnScanQrCode.setEnabled(false);
        btnGenerateTags.setEnabled(false);
        btnConfirmStorage.setEnabled(true);
    }

    @Override
    public void printFail() {
        log("二维码打印失败，请重新打印");
        ArmsUtils.makeText(getContext(), "二维码打印失败，请重新打印");
    }
}
